package models

import (
	"labix.org/v2/mgo/bson"
	"log"
)

type Group struct {
	Id     string `bson:"_id,omitempty"`
	Name   string
	ONum   int
	CNum   int
	Cgroup []Group
	Icon   string
}

//写入分组
func (this *Group) Add() error {
	defer close()
	defer exption()
	log.Println("开始写入Group")
	var c = open("Group")
	err := c.Insert(this)
	return err
}

//修改分组信息
func (this *Group) Update() error {
	defer close()
	defer exption()
	log.Println("开始更新Group")
	var c = open("Group")
	//只修改部分需要用$set否则会覆盖
	err := c.Update(bson.M{"_id": this.Id}, bson.M{"$set": bson.M{
		"name":   this.Name,
		"onum":   this.ONum,
		"cgroup": this.Cgroup,
		"icon":   this.Icon,
	}})
	return err
}

//只修改分组文章个数
func (this *Group) ChangeCount() error {
	defer close()
	defer exption()
	log.Println("开始更新Group")
	var c = open("Group")
	//只修改部分需要用$set否则会覆盖
	err := c.Update(bson.M{"_id": this.Id}, bson.M{"$set": bson.M{
		"cnum": this.CNum,
	}})
	return err
}

//移除分组
func (this *Group) Delete() error {
	defer close()
	defer exption()
	log.Println("移除分组")
	var c = open("Group")
	err := c.RemoveId(this.Id)
	return err
}

///获取一条分组信息
func (this *Group) Get() error {
	defer close()
	defer exption()
	log.Println("读取一条Group")
	var c = open("Group")
	err := c.Find(bson.M{"_id": this.Id}).One(this)
	return err
}

//获取分组信息
func (this *Group) Query() []Group {
	defer close()
	defer exption()
	log.Println("读取所有Group")
	var c = open("Group")
	result := make([]Group, 1)
	err := c.Find(bson.M{}).Sort("-_id").All(&result)
	if err != nil {
		log.Println(err)
	}
	//log.Println(result);
	return result
}
